import React from 'react';
import { connect } from 'react-redux';
import action from '../store/actions/index';
import './Task.less';
import api from '../api/index';
import moment from 'moment';
import { Button, Tag, Table, Modal, Input, DatePicker, message } from 'antd';
const { TextArea } = Input;
const { confirm } = Modal;

//=>今天之后的一天
const nowNext = moment(new Date(new Date().getTime() + (24 * 60 * 60 * 1000)).toLocaleString().replace(/[\u4E00-\u9FA5]/g, ''));

class Task extends React.Component {
	state = {
		//=>控制表格的列
		columns: [{
			title: "编号",
			dataIndex: "id",
			width: '10%'
		}, {
			title: "描述",
			dataIndex: "task",
			width: '40%'
		}, {
			title: "时间",
			width: '15%',
			render: text => {
				let { time, complete, state } = text;
				if (state == 2) {
					time = complete;
				}
				// 2020-1-11 18:00:00
				// ['2020','1','11','18','00','00']
				let timeArr = time.match(/\d+/g);
				return '{1}-{2} {3}:{4}'.replace(/\{(\d+)\}/g, (val, group1) => {
					let res = timeArr[group1] || '0';
					return res.length < 2 ? '0' + res : res;
				});
			}
		}, {
			title: "状态",
			dataIndex: "state",
			width: '15%',
			render: (text, record, index) => {
				//text:当前列展示的数据，如果没有设置dataIndex，它的值和record一样的
				//record:当前行对应的数据信息
				//index:当前行的索引
				return text == 1 ? '未完成' : '已完成';
			}
		}, {
			title: "操作",
			width: '20%',
			render: text => {
				let { state } = text;
				return <>
					<Button type="link"
						onClick={this.handleDelete.bind(this, text)}>
						删除
					</Button>
					{state == 1 ? <Button type="link">完成</Button> : null}
				</>;
			}
		}],
		//=>控制Modal的显示隐藏
		visible: false,
		//=>控制输入内容
		task: '',
		time: nowNext,
		//=>控制页卡
		tagList: [{
			state: 0,
			text: '全部',
			selected: true
		}, {
			state: 1,
			text: '未完成',
			selected: false
		}, {
			state: 2,
			text: '已完成',
			selected: false
		}]
	};
	render() {
		let { columns, visible, task, time, tagList } = this.state;
		let { taskList } = this.props;

		//根据选中态筛选要展示的数据
		let state = parseInt(localStorage.getItem('state')) || 0;
		let data = taskList;
		if (state !== 0) {
			data = data.filter(item => parseInt(item.state) === state);
		}

		return <section className="taskBox">
			<header className="headerBox">
				<h2>TASK OA 任务管理系统</h2>
				<Button type='primary' onClick={ev => {
					this.setState({ visible: true });
				}}>新增</Button>
			</header>

			<nav className="navBox" onClick={this.changeTag}>
				{tagList.map(item => {
					return <Tag state={item.state}
						key={item.state}
						color={item.selected ? '#108ee9' : ''}>
						{item.text}
					</Tag>;
				})}
			</nav>

			<Table columns={columns} dataSource={data} pagination={false} rowKey="id"></Table>

			{/* 新增的对话框 */}
			<Modal title="新增任务" visible={visible} onOk={this.submit} onCancel={this.cancel} maskClosable={false}>
				<p>任务描述：</p>
				<TextArea rows={4} value={task} onInput={ev => {
					this.setState({
						task: ev.target.value
					});
				}}></TextArea>
				<p>预期完成时间：</p>
				<DatePicker showTime onChange={ev => {
					this.setState({
						time: ev
					});
				}} value={time}></DatePicker>
			</Modal>
		</section>;
	}
	//=>删除任务
	handleDelete = text => {
		let { id } = text;
		confirm({
			title: "这是一个危险的操作",
			content: `您确定要删除编号为 ${id} 的任务信息吗？`,
			okType: 'danger',
			onOk: async () => {
				let result = await api.task.removeTask(id);
				let { code } = result;
				if (parseInt(code) === 0) {
					//成功
					message.success('恭喜您，任务删除成功~');
					this.props.deleteTask(id);
					return;
				}
				//失败
				message.error('任务删除失败，请稍后再试~');
			}
		});
	};
	//=>新增任务
	submit = async () => {
		let { task, time } = this.state;
		if (task.trim().length === 0) {
			message.warning('任务描述不能为空~~');
			return;
		}
		if (!time) {
			message.warning('预期完成时间不能为空~~');
			return;
		}
		time = time.toDate();
		time = `${time.getFullYear()}-${time.getMonth() + 1}-${time.getDate()} ${time.getHours()}:${time.getMinutes()}:${time.getSeconds()}`;
		//把信息发送给服务器
		let result = await api.task.addTask(task, time);
		let { code } = result;
		if (parseInt(code) === 0) {
			//成功
			message.success('恭喜您，新增任务成功~');
			this.cancel();
			this.props.asyncTaskList();
			return;
		}
		//失败
		message.error('新增任务失败，请稍后再试~');
	};
	cancel = () => {
		this.setState({
			visible: false,
			task: '',
			time: nowNext
		});
	};
	//=>切换页卡
	changeSelect = () => {
		let state = parseInt(localStorage.getItem('state')) || 0;
		let tagList = this.state.tagList;
		tagList = tagList.map(item => {
			item.selected = item.state === state ? true : false;
			return item;
		});
		this.setState({ tagList });
	};
	changeTag = ev => {
		let target = ev.target,
			state = target.getAttribute('state');
		if (target.tagName !== "SPAN") return;
		state = parseInt(state);
		//把当前选中结果向本地存储一份
		localStorage.setItem('state', state);
		this.changeSelect();
	};
	//=>同步服务器的全部任务信息到REDUX中
	componentWillMount() {
		this.changeSelect();
		this.props.asyncTaskList();
	}
}
export default connect(state => state.task, action.task)(Task);